package com.zhiyou.app.shop.website.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.aspectj.internal.lang.annotation.ajcDeclareAnnotation;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.annotations.Until;
import com.zhiyou.app.shop.common.BaseAction;
import com.zhiyou.app.shop.common.util.DateUtil;
import com.zhiyou.app.shop.common.util.ShopConstants;
import com.zhiyou.app.shop.website.dao.pojo.ActivityApply;
import com.zhiyou.app.shop.website.dao.pojo.DicItem;
import com.zhiyou.app.shop.website.dao.pojo.EpComplain;
import com.zhiyou.app.shop.website.dao.pojo.EpList;
import com.zhiyou.app.shop.website.dao.pojo.Loclist;
import com.zhiyou.app.shop.website.dao.pojo.Menu;
import com.zhiyou.app.shop.website.dao.pojo.MoneyDeal;
import com.zhiyou.app.shop.website.dao.pojo.Msg;
import com.zhiyou.app.shop.website.dao.pojo.News;
import com.zhiyou.app.shop.website.dao.pojo.PwdUpdateLog;
import com.zhiyou.app.shop.website.dao.pojo.StockInfo;
import com.zhiyou.app.shop.website.dao.pojo.User;
import com.zhiyou.app.shop.website.dao.pojo.UserAccount;
import com.zhiyou.app.shop.website.dao.pojo.UserBank;
import com.zhiyou.app.shop.website.dao.pojo.UserStock;
import com.zhiyou.app.shop.website.service.IActivityApplyService;
import com.zhiyou.app.shop.website.service.IDicItemService;
import com.zhiyou.app.shop.website.service.IEpComplainService;
import com.zhiyou.app.shop.website.service.IEpListService;
import com.zhiyou.app.shop.website.service.ILoclistService;
import com.zhiyou.app.shop.website.service.IMenuService;
import com.zhiyou.app.shop.website.service.IMoneyDealService;
import com.zhiyou.app.shop.website.service.IMsgService;
import com.zhiyou.app.shop.website.service.INewsService;
import com.zhiyou.app.shop.website.service.IPrizePayService;
import com.zhiyou.app.shop.website.service.IStockInfoService;
import com.zhiyou.app.shop.website.service.IStockService;
import com.zhiyou.app.shop.website.service.IUserAccountService;
import com.zhiyou.app.shop.website.service.IUserInfoService;
import com.zhiyou.app.shop.website.service.IUserManagerService;
import com.zhiyou.app.shop.website.service.IUserStockInfoService;
import com.zhiyou.app.shop.website.service.IUserStockService;

public class AdminManagerAction extends BaseAction {


	private static final long serialVersionUID = 1L;

	@Autowired
	private IMenuService menuService;
	@Autowired
	private IMsgService msgService;
	@Autowired
	private IStockInfoService stockInfoService;
	@Autowired
	private IActivityApplyService activityApplyService;
	@Autowired
	private INewsService newsService;
	@Autowired
	private IUserManagerService userManagerService;
	@Autowired
	private IDicItemService dicItemService;
	@Autowired
	private IUserAccountService userAccountService;
	@Autowired
	private IUserInfoService userInfoService;
	@Autowired
	private ILoclistService loclistService;
	@Autowired
	private IEpListService epListService;
	@Autowired
	private IMoneyDealService moneyDealService;
	@Autowired
	private IUserStockInfoService userStockInfoService;
	@Autowired
	private IPrizePayService prizePayService;
	@Autowired
	private IStockService stockService;
	@Autowired
	private IUserStockService userStockService;
	@Autowired
	private IEpComplainService epComplainService;
	
	private String r; //随机参数，刷新验证码
	private String randcode;
	private String username;
	private String password;
	private String loginMsg;
	private String loginReturn;
	
	private User user;
	
	private String periods;
	private StockInfo stockInfo;
	private String id;
	
	private List<DicItem> mailList;
	private List<DicItem> newsList;
	private List<DicItem> levelList;
	private List<DicItem> locationList;
	
	private DicItem dicItem;
	
	private JsonArray treedata = new JsonArray();
	private String reAccount;
	
	private News news;
	private Msg msg;
	
	private String type;
	private String account;
	private String userId;
	
	private JsonArray menudate = new JsonArray();
	
	public String authLogin(){   //管理员登陆验证
		loginReturn = "login-failure";
		if (username != null && password!= null) {
			User user = new User();
			user.setUserAccount(username);
			user.setFirstPwd(encodePassword(password));
			user.setFlag(ShopConstants.TRUE);
			user.setActivity(ShopConstants.TRUE);
			user.setRole("5");
			// 根据用户名和密码获取用户列表
			try {
				List<User> list = userManagerService.login(user);
				if (list != null && list.size() > 0) {
					String imageRand = (String) getHttpSession().getAttribute("rand");
					if(imageRand != null && (!imageRand.equals(randcode))){
						loginMsg = "验证码错误!";
					}else{
						getSession().put(ShopConstants.ADMIN_LOGIN_USER, list.get(0));
						pageSize = 15;
						newsService.getNews(getInitedPage());
						loginReturn = SUCCESS;
					}
				} else {
					loginMsg = "帐号或者密码错误!";
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			loginMsg = "帐号或者密码不可以为空!";
		}
		return loginReturn;
	
	}
	
	public String exit(){
		getSession().remove(ShopConstants.ADMIN_LOGIN_USER);
		return SUCCESS;
	}
	
	public String index(){
		List<Menu> menuList = null;
		try {
			menuList = menuService.findMenu();
		} catch (Exception e) {
			e.printStackTrace();
		}
		User admin = getCurAdmin();
		//根节点是当前用户
		for (Menu menu : menuList) {
			JsonObject o = new JsonObject();
			o.addProperty("id", menu.getMenuId());
			o.addProperty("pId", menu.getParentId());
			o.addProperty("name", menu.getResrcName());
			o.addProperty("tourl", menu.getResrcLink());
			//o.addProperty("open", true);
			menudate.add(o);
		}
		
		return SUCCESS;
	}
	//收件箱
	public String recieveMsgList(){
		User user = userManagerService.findAdmin();
		msgService.findReceiveMsg(getInitedPage(), user.getUserAccount());
		return SUCCESS;
	}
	//显示未回复的
	public String receiveMsg(){
		User user = userManagerService.findAdmin();
		msgService.findNoreply(getInitedPage(), user.getUserAccount());
		return SUCCESS;
	}
	
	//发件箱
	public String sendMsgList(){
		msgService.findsendMsg(getInitedPage(),"客服");
		return SUCCESS;
	}
	//查看邮件
	public String msgInfo(){
		msg = msgService.findById(id);
		msg.setIsRead(ShopConstants.TRUE);
		msg.setReadDate(new Timestamp(new Date().getTime()));
		msgService.update(msg);
		return SUCCESS;
	}
	//写邮件  或  回复邮件
	public String sendMsgPage(){
		mailList = dicItemService.findByType(ShopConstants.MAIL_TYPE);
		if(id != null && !"".equals(id)){
			msg = msgService.findById(id);
			msg.setTitle("答复："+msg.getTitle());			
		}
		return SUCCESS;
	}
	public String sendMsg(){
		msg.setCreateDate(new Timestamp(System.currentTimeMillis()));
		msg.setFlag(ShopConstants.TRUE);
		msg.setIsRead(ShopConstants.FALSE);
		msg.setSendId("客服");
		msgService.sendMsg(msg);
		return SUCCESS;
	}
	
	//会员投诉
	public String findComplain(){
		pageSize = 10;
		User user = userManagerService.findAdmin();
		msgService.findComplain(getInitedPage(), user.getUserAccount());
		return SUCCESS;
	}
	
	public String complaininfo(){
		msg = msgService.findById(id);
		return SUCCESS;
	}
	public String complainhandle(){
		Msg complain = msgService.findById(id);
		complain.setIsRead(ShopConstants.TRUE);
		msgService.update(complain);
		return SUCCESS;
	}
	
	private EpList ep;
	private String  buyAccount;
	private String saleAccount;
	private List epList;
	private int totalCount;
	//EP管理
	public String findEp(){
		//epListService.findEp(getInitedPage(), ep);
		pageSize = 15;
		int pageOffset = new Integer(pageNo) != null ? (pageNo-1) * pageSize : 0;
		//moneyList = moneyDealService.findMoneyDeal(account, subjectType, startDate, endDate, pageOffset, pageSize);
		epList = epListService.findEpList(buyAccount, saleAccount, pageOffset, pageSize);
		pageNo = pageOffset/pageSize + 1;
		totalCount  =epListService.findEpListCnt(buyAccount, saleAccount);
		totalPage = totalCount%pageSize!=0?totalCount/pageSize+1:totalCount/pageSize;
		return SUCCESS;
	}
	
	public String stockConfPage(){
		try {
			stockInfoService.findStockInfo(getInitedPage());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	public String updateStockConfPage(){
		if(periods == null){
			stockInfo = new StockInfo();			
			stockInfo.setPeriods(stockInfoService.findMaxPeriods()+1);
		}else{
			stockInfo = stockInfoService.findByPeriods(new Integer(periods));		
		}
		return SUCCESS;
	}
	
	public String updateStockConf(){
		if(stockInfo.getId() == null || "".equals(stockInfo.getId())){
			stockInfoService.saveStockInfo(stockInfo);			
		}else{
			stockInfoService.update(stockInfo);
		}
		return SUCCESS;
	}
	
	//报单功能
	public String applyActivityList(){
		pageSize = 10;
		activityApplyService.findApply(getInitedPage(), null);
		return SUCCESS;
	}
	public String checkApply(){
		activityApplyService.saveApplyInfo(id);
		return SUCCESS;
	}

	//新闻
	public String newsList(){
		newsList = dicItemService.findByType(ShopConstants.NEWS_TYPE);
		newsService.getNews(getInitedPage());
		return SUCCESS;
	}
	public String newsInfo(){
		newsList = dicItemService.findByType(ShopConstants.NEWS_TYPE);
		news = newsService.findById(id);
		return SUCCESS;
	}
	public String sendNewsPage(){
		newsList = dicItemService.findByType(ShopConstants.NEWS_TYPE);
		return SUCCESS;
	}
	public String sendNews(){
		news.setCreateDate(new Timestamp(System.currentTimeMillis()));
		news.setFlag(ShopConstants.TRUE);
		news.setWriterId(getCurAdmin().getUserAccount());
		newsService.saveNews(news);
		return SUCCESS;
	}
	
	//推荐图谱
	public String recommend(){
		User user = userManagerService.findAdmin();
		//根节点是当前用户
		JsonObject po = new JsonObject();
		po.addProperty("id", user.getUserAccount());
		po.addProperty("pId", "0");
		System.out.println();
		po.addProperty("name", "会员ID："+user.getUserAccount()+"，级别："+user.getLevel()+"，类型："+((ShopConstants.TRUE.equals(user.getActivity()))?ShopConstants.FULL_MEMBER:ShopConstants.NON_MEMBER)+"，直接下属："+userManagerService.getRecommendCnt(user.getUserAccount()));
		po.addProperty("open", true);
		treedata.add(po);
		List<User> recommendList = userManagerService.getRecommend(user.getUserAccount());
		/*List<User> recommendList = new ArrayList<User>();
		recommendList = findUser(recommendList, user.getUserAccount());*/
		for (User recommend : recommendList) {
			JsonObject o = new JsonObject();
			int cnt = userManagerService.getRecommendCnt(recommend.getUserAccount());
			o.addProperty("id", recommend.getUserAccount());
			o.addProperty("pId", recommend.getRecommendId());
			o.addProperty("name", "会员ID："+recommend.getUserAccount()+"，级别："+recommend.getLevel()+"，类型："+((ShopConstants.TRUE.equals(recommend.getActivity()))?ShopConstants.FULL_MEMBER:ShopConstants.NON_MEMBER)+"，直接下属："+userManagerService.getRecommendCnt(recommend.getUserAccount()));
			if(cnt > 0){
				o.addProperty("isParent", true);						
			}
			treedata.add(o);
		}
		return SUCCESS;
	}
	public String findChild(){
		//isParent
		getResponse().setContentType("text/html; charset=UTF-8");
		try {
			JsonArray treedata = new JsonArray ();
			List<User> recommendList = userManagerService.getRecommend(reAccount);
			if(recommendList != null && recommendList.size() >0){
				for (User recommend : recommendList) {
					JsonObject o = new JsonObject();
					int cnt = userManagerService.getRecommendCnt(recommend.getUserAccount());
					o.addProperty("id", recommend.getUserAccount());
					o.addProperty("pId", recommend.getRecommendId());
					o.addProperty("name", "会员ID："+recommend.getUserAccount()+"，级别："+recommend.getLevel()+"，类型："+((ShopConstants.TRUE.equals(recommend.getActivity()))?ShopConstants.FULL_MEMBER:ShopConstants.NON_MEMBER)+"，直接下属："+cnt);
					if(cnt > 0){
						o.addProperty("isParent", true);						
					}
					treedata.add(o);
				}			
			}
			getResponse().getWriter().print(treedata);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	private String location;
	private Integer floor;
	//用户关系图
	public String relation(){
		User user = null;
		if(id == null || "".equals(id)){
			user = userManagerService.findAdmin();			
		}else{
			user = userManagerService.getUserByAccount(id);
			//userManagerService.getUserById(id);
		}
		if(floor == null || "".equals(floor))
			floor = 3;
		location = test1(user,floor);
		return SUCCESS;
	}
	private String test1(User user,int floor){//递归取
		StringBuilder result = new StringBuilder("<table border='0'><tr align='center'><td colspan='2'>"+test2(user)+"</td></tr>");
		floor -= 1;
		if(floor >0){
			result.append(test3());
			List<User> users = userManagerService.getRedirectChild(user.getUserAccount());
			result.append("<tr valign ='top'>");
			if(users == null || users.size() ==0){ //没有子节点
				result.append("<td>"+test4(user,"1")+"</td>");
				result.append("<td>"+test4(user,"2")+"</td>");
			}else if(users.size() ==1){ //有一个子节点
				//判断左边还是右边
				if("1".equals(users.get(0).getLocation())){  //左边
					result.append("<td>"+test1(users.get(0),floor)+"</td>");
					result.append("<td>"+test4(user,"2")+"</td>");
				}else{  //右边
					result.append("<td>"+test4(user,"1")+"</td>");
					result.append("<td>"+test1(users.get(0),floor)+"</td>");
				}
				
			}else{
				for(User u:users){
					result.append("<td>"+test1(u,floor)+"</td>");
				}				
			}
		}
		result.append("</tr>");
		result.append("</table>");
		return result.toString();
	}
	
	private String test2(User  u){
		String activityFlag = u.getActivity();
		if(activityFlag == null || "".equals(activityFlag)){
			activityFlag = "(未激活)";			
		}else{
			activityFlag = "";
		}
		String level = dicItemService.findByTypeAndCode(ShopConstants.LEVEL, u.getLevel()).getName();
		StringBuilder result = new StringBuilder("<table border='0' width='200' cellpadding='0' cellspacing='1' bgcolor='#cacaca'><tr><td colspan='2' bgcolor='#f0f0f0' align='center'><a href='relation.action?id="+u.getUserAccount()+"'>"+u.getUserAccount()+"</a>"+activityFlag+"</td></tr>"
				+ "<tr><td colspan='2' bgcolor='#FFFFFF' align='center'>"+level+"</td></tr>"
				+ "<tr><td colspan='2' bgcolor='#FFFFFF' align='center'>"+DateUtil.getDate(u.getRegisterDate(), "yyyy-M-dd hh:mm:ss")+"</td></tr>"
				+ "<tr><td bgcolor='#FFFFFF' align='center'>"+u.getSparelAmount().intValue()+"("+u.getSparel()+")</td>" 
				+     "<td bgcolor='#FFFFFF' align='center'>"+u.getApaerAmount().intValue()+"("+u.getSparer()+")</td></tr>"
				+ "<tr><td bgcolor='#FFFFFF' align='center'>"+u.getLeftLeaveAmount().intValue()+"("+u.getLeftLeave()+")</td>"
				+     "<td bgcolor='#FFFFFF' align='center'>"+u.getRightLeaveAmount().intValue()+"("+u.getRightLeave()+")</td></tr></table>");	
		return result.toString();
	}
	
	private String test4(User u,String location){
		String activityFlag = u.getActivity();
		if(activityFlag == null || "".equals(activityFlag)){//父节点未激活  不能注册
			activityFlag = "";			
		}else{  
			activityFlag = "<a href='javascript:void(0);' onclick='parent.location.href="+getRequest().getContextPath()+"/other.action?parentId="+u.getUserAccount()+"&location="+location+"'>注册</a>";
		}
		StringBuilder result = new StringBuilder("<table border='0'><tr align='center'><td colspan='2'>  "
					+"<table width='200' border='0' cellpadding='0' cellspacing='1' bgcolor='#ed1b2f'>"
					+"<tr><td height='24' style='text-align:center; color:#fff;'>"+activityFlag+"</td></tr>"
					+"<tr><td height='80' bgcolor='#FFFFFF'>&nbsp;</td></tr></table></td></tr></table>");
		return result.toString();
	}
	private String test3(){//划线Z
		/*StringBuilder result = new StringBuilder("<tr><td align='center' colspan='2'><img height='20' src='"+getRequest().getContextPath()+"/resources/images/t_tree_top.gif'/></td></tr>");
		result.append("<tr><td><img width='25%' height='20' align='right' src='"+getRequest().getContextPath()+"/resources/images/t_tree_line.gif'/></td>" +
				"<td><img width='25%' height='20' align='left' src='"+getRequest().getContextPath()+"/resources/images/t_tree_line.gif'/></td></tr>");
		
		result.append("<tr><td><img height='25' align='center' src='"+getRequest().getContextPath()+"/resources/images/t_tree_bottom_l.gif' complete='complete'/></td>" +
				"<td><img height='25' align='center' src='"+getRequest().getContextPath()+"/resources/images/t_tree_bottom_r.gif' complete='complete'/></td></tr>");*/
		StringBuilder result = new StringBuilder();
		result.append("<tr><td width='100%' align='center' colspan='2' valign ='top'>" +
				"<img height='30' src='"+getRequest().getContextPath()+"/resources/images/t_tree_bottom_l.gif' complete='complete'/>"
				+"<img width='25%' height='30' src='"+getRequest().getContextPath()+"/resources/images/t_tree_line.gif' complete='complete'/>"
				+"<img height='30' src='"+getRequest().getContextPath()+"/resources/images/t_tree_top.gif' complete='complete'/>"
				+"<img width='25%' height='30' src='"+getRequest().getContextPath()+"/resources/images/t_tree_line.gif' complete='complete'/>"
				+"<img height='30' src='"+getRequest().getContextPath()+"/resources/images/t_tree_bottom_r.gif'/></td></tr>");
		return result.toString();
	}
	//TODO 
	
	//用户账户情况
	public String userList(){
		levelList = dicItemService.findByType(ShopConstants.LEVEL);
		locationList = dicItemService.findByType(ShopConstants.LOCATION);
		if("1".equals(type)){   //进入新增
			if(user == null){
				user = new User();
			}
			user.setRegisterDate(new Timestamp(System.currentTimeMillis()));
		}
		try {
			userInfoService.findUser(getInitedPage(), user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	private String[] userIds;
	//标记为公司账号
	public String markUser(){
		getResponse().setContentType("text/html; charset=UTF-8");
		try {
			userInfoService.markUser(userIds, type);
			PrintWriter out = getResponse().getWriter();
			out.print("操作成功");
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//报单方式是  彩票 的用户情况
	public String findLottery(){
		levelList = dicItemService.findByType(ShopConstants.LEVEL);
		locationList = dicItemService.findByType(ShopConstants.LOCATION);
		try {
			userInfoService.findUser(getInitedPage(), user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	private List<DicItem> levels;
	private float prize; //股票价格
	//进入到前台页面
	public String enterMember(){
		User user = new User();
		user.setUserAccount(username);
		user.setFirstPwd(password);
		// 根据用户名和密码获取用户列表
		try {
			List<User> list = userManagerService.login(user);
			if (list != null && list.size() > 0) {
				getSession().put(ShopConstants.LOGIN_USER, list.get(0));
				levels = dicItemService.findByType(ShopConstants.LEVEL);
				pageSize = 8;
				newsService.getNews(getInitedPage());
				prize = stockService.findPrice();
				loginReturn = SUCCESS;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	private UserAccount useraccount;
	//用户账户信息查询
	public String userAccount(){
		try {
			useraccount = userAccountService.findByUserAccount(account);
			Long userStockA = userStockService.findUserStock(account, "1");//旧股
			Long userStockB = userStockService.findUserStock(account, "2");//新股
			useraccount.setStockNum(userStockA.intValue());
			useraccount.setStockSaleNum(userStockB.intValue());
		} catch (Exception e) {
			e.printStackTrace();
		}
		/*Long userStock = userStockService.findUserStock(account);
		if(userStock != null){
			useraccount.setStockSaleNum(userStock.intValue());
		}else{
			useraccount.setStockSaleNum(0);
		}*/
		return SUCCESS;
	}
	
	private String password11;
	private String password21;
	private String password31;
	//用户密码修改
	public String toModifyPwd(){
		if("1".equals(type) && ("".equals(userId) || userId == null)){
			userId = getCurAdmin().getUserId();
		}
		user = userManagerService.getUserById(userId);
		if("1".equals(type)){
			return "modifypwd";
		}
		return SUCCESS;
	}
	public String modifyPwd(){
		getResponse().setContentType("text/html; charset=UTF-8");
		User user = userManagerService.getUserById(userId);  //通过主键id获取
		PwdUpdateLog pwd1 = null;
		PwdUpdateLog pwd2 = null;
		PwdUpdateLog pwd3 = null;
		Timestamp time = new Timestamp(System.currentTimeMillis());
		if(!"".equals(password11)){
			pwd1 = new PwdUpdateLog();
			pwd1.setUserId(user.getUserAccount());
			pwd1.setOld(user.getFirstPwd());
			pwd1.setNews(password11);
			pwd1.setUpdateTime(time);
			pwd1.setType("1");
			pwd1.setUpdateBy(getCurAdmin().getUserAccount());
			pwd1.setIpAddress(getIpAddr(getRequest()));
			user.setFirstPwd(encodePassword(password11));
			DicItem dicItem = dicItemService.findByTypeAndCode(ShopConstants.XMPP, "0");
			String xmppurl = "http://"+dicItem.getName()+"/MobileAdmin/iface/user/changeUserPwd.shtml";
			try {
				HttpPost post = new HttpPost(xmppurl);
				//添加参数
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("nickname", user.getUserAccount().toLowerCase()));
				params.add(new BasicNameValuePair("password", encodePassword(password11)));
				post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				//发送请求
				HttpClient http = new DefaultHttpClient();
				HttpResponse response = http.execute(post);
				/*HttpEntity entity = response.getEntity();
				System.out.println("Login form get: " + response.getStatusLine() + entity.getContent());
				System.out.println(response.getStatusLine().getStatusCode());*/
				if(response.getStatusLine().getStatusCode() == 200){
					/*String results = EntityUtils.toString(response.getEntity());
					Gson gson = new Gson();
					JsonArray array = new JsonArray();*/
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(!"".equals(password21)){
			pwd2 = new PwdUpdateLog();
			pwd2.setUserId(user.getUserAccount());
			pwd2.setOld(user.getSecondPwd());
			pwd2.setNews(password21);
			pwd2.setUpdateTime(time);
			pwd2.setType("2");
			pwd2.setUpdateBy(getCurAdmin().getUserAccount());
			pwd2.setIpAddress(getIpAddr(getRequest()));
			user.setSecondPwd(encodePassword(password21));
		}
		if(!"".equals(password31)){
			pwd3 = new PwdUpdateLog();
			pwd3.setUserId(user.getUserAccount());
			pwd3.setOld(user.getThirdPwd());
			pwd3.setNews(password31);
			pwd3.setUpdateTime(time);
			pwd3.setType("3");
			pwd3.setUpdateBy(getCurAdmin().getUserAccount());
			pwd3.setIpAddress(getIpAddr(getRequest()));
			user.setThirdPwd(encodePassword(password31));
		}
		userInfoService.savePwd(user, pwd1, pwd2, pwd3);
		try {
			PrintWriter out = getResponse().getWriter();
			out.print("修改成功!");
			out.flush();
			out.close();
		} catch (IOException e) {
		}
		return null;
	}
	
	private String getIpAddr(HttpServletRequest request) { 
	       String ip = request.getHeader("x-forwarded-for"); 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getHeader("Proxy-Client-IP"); 
	       } 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getHeader("WL-Proxy-Client-IP"); 
	       } 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getRemoteAddr(); 
	       } 
	       return ip; 
	   } 
	
	private UserBank userBank;
	private List<DicItem> bankList;
	private List<Loclist> listCountry;
	//用户银行卡修改
	public String toModifyBank(){
		bankList = dicItemService.findByType(ShopConstants.BANK_TYPE);		
		listCountry = loclistService.getConutry();
		if(account == null || "".equals(account)){
			User user = userManagerService.findAdmin();
			account = user.getUserAccount();
		}
		userBank = userManagerService.findByAccount(account);
		return SUCCESS;
	}
	
	private String bankType;
	private String bankName1;
	private String bankName2;
	public String modifyBank(){
		getResponse().setContentType("text/html; charset=UTF-8");
		UserBank bank = userManagerService.findByAccount(account);
		//bank.setBankName(userBank.getBankName());
		bank.setBankCountry(userBank.getBankCountry());
		bank.setBankProvince(userBank.getBankProvince());
		bank.setSubBranch(userBank.getSubBranch());
		bank.setBankUser(userBank.getBankUser());
		bank.setBankCard(userBank.getBankCard());
		if("1".equals(bankType)){//从给定的银行中选
			bank.setBankName(bankName1);
		}else{ //自定义银行
			bank.setBankName(bankName2);
		}
		userManagerService.saveUserBank(bank);
		try {
			PrintWriter out = getResponse().getWriter();
			out.print("修改成功!");
			out.flush();
			out.close();
		} catch (IOException e) {
		}
		return null;
	}
	
	private String chargeType;
	private String accountType;
	private String chargeAmount;
	private String remark;
	private List<DicItem> chargeList;
	private List<DicItem> accountList;
	private List<DicItem> accountSubList;
	//充值 / 扣款
	public String reCharge(){
		pageSize = 10;
		chargeList = dicItemService.findByType(ShopConstants.CHARGE);
		accountSubList = dicItemService.findByType(ShopConstants.CHARGE_ACCOUNT);
		accountList = dicItemService.findByType(ShopConstants.ACCOUNT_TYPE);
		moneyDealService.findCharge(getInitedPage(), account, accountType, subjectType);
		return SUCCESS;
	}
	public String doCharge(){
		User user = userInfoService.findByAccount(account);
		UserAccount userAccount = userAccountService.findByUserAccount(account);
		BigDecimal amount = new BigDecimal(chargeAmount);
		MoneyDeal deal = new MoneyDeal();
		deal.setCreateDate(new Timestamp(System.currentTimeMillis()));
		deal.setUserId(user.getUserId());
		//deal.setRemark(remark);
		if("1".equals(chargeType)){  //充值
			deal.setSubjectType("7"); //充值
			if("1".equals(accountType)){ //激活豆
				userAccount.setActivMoney(userAccount.getActivMoney().add(amount));
				deal.setAccountType(ShopConstants.ACTIVITY);
				deal.setAccountSubject("激活豆充值"); //
				deal.setRemark(user.getUserAccount());
				deal.setIncome(amount);
			}else if("2".equals(accountType)){  //咖啡豆
				userAccount.setBonusMoney(userAccount.getBonusMoney().add(amount));
				deal.setAccountType(ShopConstants.PRIZE);
				deal.setAccountSubject("咖啡豆充值"); //
				deal.setRemark(user.getUserAccount());
				deal.setIncome(amount);
			}else if("3".equals(accountType)){  //游戏豆
				userAccount.setStockMoney(userAccount.getStockMoney().add(amount));
				deal.setAccountType(ShopConstants.STOCK);
				deal.setAccountSubject("游戏豆充值"); //
				deal.setRemark(user.getUserAccount());
				deal.setIncome(amount);
			}else if("4".equals(accountType)){  //重消  仙草豆
				userAccount.setConsumerMoney(userAccount.getConsumerMoney().add(amount));
				deal.setAccountType(ShopConstants.RESUMER);
				deal.setAccountSubject("仙草豆充值"); //
				deal.setRemark(user.getUserAccount());
				deal.setIncome(amount);
			}else if("5".equals(accountType)){  //加单  VV豆
				userAccount.setAdditionMoney(userAccount.getAdditionMoney().add(amount));
				deal.setAccountType(ShopConstants.ADD);
				deal.setAccountSubject("VV豆充值");  //
				deal.setRemark(user.getUserAccount());
				deal.setIncome(amount);
			}
		}else{  //扣款
			deal.setSubjectType("8"); //扣款
			if("1".equals(accountType)){ //激活豆
				userAccount.setActivMoney(userAccount.getActivMoney().subtract(amount));
				deal.setAccountType(ShopConstants.ACTIVITY);
				deal.setAccountSubject("激活豆扣款"); //
				deal.setRemark(user.getUserAccount());
				deal.setPay(amount);
			}else if("2".equals(accountType)){  //咖啡豆
				userAccount.setBonusMoney(userAccount.getBonusMoney().subtract(amount));
				deal.setAccountType(ShopConstants.PRIZE);
				deal.setAccountSubject("咖啡豆扣款"); //
				deal.setRemark(user.getUserAccount());
				deal.setPay(amount);
			}else if("3".equals(accountType)){  //游戏豆
				userAccount.setStockMoney(userAccount.getStockMoney().subtract(amount));
				deal.setAccountType(ShopConstants.STOCK);
				deal.setAccountSubject("游戏豆扣款"); //
				deal.setRemark(user.getUserAccount());
				deal.setPay(amount);
			}else if("4".equals(accountType)){  //重消  仙草豆
				userAccount.setConsumerMoney(userAccount.getConsumerMoney().subtract(amount));
				deal.setAccountType(ShopConstants.RESUMER);
				deal.setAccountSubject("仙草豆扣款"); //
				deal.setRemark(user.getUserAccount());
				deal.setPay(amount);
			}else if("5".equals(accountType)){  //加单  VV豆
				userAccount.setAdditionMoney(userAccount.getAdditionMoney().subtract(amount));
				deal.setAccountType(ShopConstants.ADD);
				deal.setAccountSubject("VV豆扣款");  //
				deal.setRemark(user.getUserAccount());
				deal.setPay(amount);
			}
		}
		userAccountService.doCharge(userAccount, deal);
		getResponse().setContentType("text/html; charset=UTF-8");
		PrintWriter out;
		try {
			out = getResponse().getWriter();
			out.print("操作成功!");
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public String chargeList(){

		chargeList = dicItemService.findByType(ShopConstants.CHARGE);
		accountList = dicItemService.findByType(ShopConstants.ACCOUNT_TYPE);
		moneyDealService.findCharge(getInitedPage(), account, accountType, subjectType);
		return SUCCESS;
	}
	
	private String subjectType;
	private String startDate;
	private String endDate;
	private Integer totalPage;
	private List moneyList;
	//财务流水
	public String currDeal(){
		try {
			levelList = dicItemService.findByType(ShopConstants.LEVEL);
			pageSize = 15;
			int pageOffset = new Integer(pageNo) != null ? (pageNo-1) * pageSize : 0;
			moneyList = moneyDealService.findMoneyDeal(account, subjectType, startDate, endDate, pageOffset, pageSize);
			pageNo = pageOffset/pageSize + 1;
			totalCount  = moneyDealService.findMoneyDealCnt(account, subjectType, startDate, endDate);
			totalPage = totalCount%pageSize!=0?totalCount/pageSize+1:totalCount/pageSize;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	private String price1;
	private String price2;
	//
	public String userStockList(){
		userStockInfoService.findUserStock(getInitedPage(), account, accountType, price1, price2,startDate, endDate, "");
		return SUCCESS;
	}
	
	//修改管理员密码
	public String modifyAdminPwd(){
		
		return SUCCESS;
	}
	
	private List accountRateList;
	//拨出比例
	public String accountRate(){
		pageSize=15;
		int pageOffset = new Integer(pageNo) != null ? (pageNo-1) * pageSize : 0;
		accountRateList = prizePayService.findPrizePay(pageOffset, pageSize);
		pageNo = pageOffset/pageSize + 1;
		totalCount = prizePayService.findPrizePayCnt();
		totalPage = totalCount%pageSize!=0?totalCount/pageSize+1:totalCount/pageSize;
		return SUCCESS;
	}
	private String level;
	//工资汇总
	public String prizePay(){
		try {
			levelList = dicItemService.findByType(ShopConstants.LEVEL);
			int pageOffset = new Integer(pageNo) != null ? (pageNo-1) * pageSize : 0;
			accountRateList = prizePayService.findPrize(accountType, level, startDate, endDate, pageOffset, pageSize);
			pageNo = pageOffset/pageSize + 1;
			totalCount = prizePayService.findprizeCnt(accountType, level, startDate, endDate);
			totalPage = totalCount%pageSize!=0?totalCount/pageSize+1:totalCount/pageSize;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public String deletenews(){
		news = newsService.findById(id);
		newsService.delete(news);
		return newsList();
	}
	private String json;
	public String supportEp(){
		if(id != null && !"".equals(id) && account != null && !"".equals(account)){
			try{
				ep = epListService.findbyId(id);
				useraccount = userAccountService.findByUserAccount(account);
				if("1".equals(type)){ //退回给卖方
					useraccount.setBonusMoney(useraccount.getBonusMoney().add(ep.getNeedAmont()));
					//ep.setStatus("4");  //撤销ep交易    冻结中的奖金币返回给卖方
					//或者删除ep记录
					epListService.delete(ep);
					userAccountService.saveAccount(useraccount);
					//epListService.update(ep);
				}else if("2".equals(type)){  //给买方
					useraccount.setBonusMoney(useraccount.getBonusMoney().add(ep.getDealAmount()).add(ep.getPostFee()));
					ep.setStatus("3");  //交易成功
					ep.setSuccessDate(new Timestamp(System.currentTimeMillis()));
					userAccountService.saveAccount(useraccount);
					epListService.update(ep);
				}	
				json = "1";
				return SUCCESS;
			}catch(Exception e){
				json = "0";
			}
		}else{
			json = "0";
		}
		return "eplist";
	}
	
	//用户账户情况
	public String userAccountList(){
		//userAccountService.fin
		return SUCCESS;
	}
	
	private String thirdPassword;
	public String checkThirdPwd(){
		getResponse().setContentType("text/html; charset=UTF-8");
		User user = getCurAdmin();
		if(!user.getThirdPwd().equals(encodePassword(thirdPassword))){
			try {
				getResponse().getWriter().print("原来三级密码输入错误!");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	private EpComplain epComplain;
	public String complain(){
		epComplain = epComplainService.findById(Integer.parseInt(id));
		return SUCCESS;
	}
	
	public String handleComplain(){
		EpComplain epc =epComplainService.findById(epComplain.getId());
		ep = epListService.findbyId(epc.getEpId());
		ep.setComplainStatus("2");  //已处理
		epc.setResult(epComplain.getResult());
		epc.setHandleDate(new Timestamp(System.currentTimeMillis()));
		epc.setHandle("0");
		epListService.saveEpComplain(ep, epc);
		getResponse().setContentType("text/html; charset=UTF-8");
		PrintWriter out;
		try {
			out = getResponse().getWriter();
			out.print("投诉已处理!");
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//数据字典
	public String dicItemInfo(){
		dicItem = dicItemService.findByTypeAndCode(ShopConstants.EXCHANG_STOCK_RATE, "1");
		return SUCCESS;
	}
	
	private String name;
	public String updateItem(){
		getResponse().setContentType("text/html; charset=UTF-8");
		try {
			PrintWriter out = getResponse().getWriter();
			DicItem dicItem = dicItemService.findbyId(id);
			dicItem.setName(name);
			dicItemService.update(dicItem);
			out.print("修改成功");
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public JsonArray getMenudate() {
		return menudate;
	}

	public void setMenudate(JsonArray menudate) {
		this.menudate = menudate;
	}

	public String getPeriods() {
		return periods;
	}

	public void setPeriods(String periods) {
		this.periods = periods;
	}

	public StockInfo getStockInfo() {
		return stockInfo;
	}

	public void setStockInfo(StockInfo stockInfo) {
		this.stockInfo = stockInfo;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public List<DicItem> getMailList() {
		return mailList;
	}

	public void setMailList(List<DicItem> mailList) {
		this.mailList = mailList;
	}

	public List<DicItem> getNewsList() {
		return newsList;
	}

	public void setNewsList(List<DicItem> newsList) {
		this.newsList = newsList;
	}

	public News getNews() {
		return news;
	}

	public void setNews(News news) {
		this.news = news;
	}
	public Msg getMsg() {
		return msg;
	}
	public void setMsg(Msg msg) {
		this.msg = msg;
	}
	public JsonArray getTreedata() {
		return treedata;
	}
	public void setTreedata(JsonArray treedata) {
		this.treedata = treedata;
	}
	public String getReAccount() {
		return reAccount;
	}
	public void setReAccount(String reAccount) {
		this.reAccount = reAccount;
	}

	public String getR() {
		return r;
	}

	public void setR(String r) {
		this.r = r;
	}

	public String getRandcode() {
		return randcode;
	}

	public void setRandcode(String randcode) {
		this.randcode = randcode;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getLoginMsg() {
		loginMsg = getText(loginMsg);
		return loginMsg;
	}

	public void setLoginMsg(String loginMsg) {
		this.loginMsg = loginMsg;
	}

	public String getLoginReturn() {
		return loginReturn;
	}

	public void setLoginReturn(String loginReturn) {
		this.loginReturn = loginReturn;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public String getPassword11() {
		return password11;
	}

	public void setPassword11(String password11) {
		this.password11 = password11;
	}

	public String getPassword21() {
		return password21;
	}

	public void setPassword21(String password21) {
		this.password21 = password21;
	}

	public String getPassword31() {
		return password31;
	}

	public void setPassword31(String password31) {
		this.password31 = password31;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public UserBank getUserBank() {
		return userBank;
	}

	public void setUserBank(UserBank userBank) {
		this.userBank = userBank;
	}

	public List<DicItem> getBankList() {
		return bankList;
	}

	public void setBankList(List<DicItem> bankList) {
		this.bankList = bankList;
	}

	public List<Loclist> getListCountry() {
		return listCountry;
	}

	public void setListCountry(List<Loclist> listCountry) {
		this.listCountry = listCountry;
	}

	public String getChargeType() {
		return chargeType;
	}

	public void setChargeType(String chargeType) {
		this.chargeType = chargeType;
	}

	public String getAccountType() {
		return accountType;
	}

	public void setAccountType(String accountType) {
		this.accountType = accountType;
	}

	public String getChargeAmount() {
		return chargeAmount;
	}

	public void setChargeAmount(String chargeAmount) {
		this.chargeAmount = chargeAmount;
	}

	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	public List<DicItem> getChargeList() {
		return chargeList;
	}

	public void setChargeList(List<DicItem> chargeList) {
		this.chargeList = chargeList;
	}

	public List<DicItem> getAccountList() {
		return accountList;
	}

	public void setAccountList(List<DicItem> accountList) {
		this.accountList = accountList;
	}

	public EpList getEp() {
		return ep;
	}

	public void setEp(EpList ep) {
		this.ep = ep;
	}

	public String getLocation() {
		return location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	public Integer getFloor() {
		return floor;
	}

	public void setFloor(Integer floor) {
		this.floor = floor;
	}

	public String getSubjectType() {
		return subjectType;
	}

	public void setSubjectType(String subjectType) {
		this.subjectType = subjectType;
	}

	public String getStartDate() {
		return startDate;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public String getEndDate() {
		return endDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public Integer getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(Integer totalPage) {
		this.totalPage = totalPage;
	}

	public List getMoneyList() {
		return moneyList;
	}

	public void setMoneyList(List moneyList) {
		this.moneyList = moneyList;
	}

	public String getPrice1() {
		return price1;
	}

	public void setPrice1(String price1) {
		this.price1 = price1;
	}

	public String getPrice2() {
		return price2;
	}

	public void setPrice2(String price2) {
		this.price2 = price2;
	}

	public List<DicItem> getLevelList() {
		return levelList;
	}

	public void setLevelList(List<DicItem> levelList) {
		this.levelList = levelList;
	}

	public List getAccountRateList() {
		return accountRateList;
	}

	public void setAccountRateList(List accountRateList) {
		this.accountRateList = accountRateList;
	}

	public String getLevel() {
		return level;
	}

	public void setLevel(String level) {
		this.level = level;
	}

	public List<DicItem> getLocationList() {
		return locationList;
	}

	public void setLocationList(List<DicItem> locationList) {
		this.locationList = locationList;
	}

	public UserAccount getUseraccount() {
		return useraccount;
	}

	public void setUseraccount(UserAccount useraccount) {
		this.useraccount = useraccount;
	}

	public String getBankType() {
		return bankType;
	}

	public void setBankType(String bankType) {
		this.bankType = bankType;
	}

	public String getBankName1() {
		return bankName1;
	}

	public void setBankName1(String bankName1) {
		this.bankName1 = bankName1;
	}

	public String getBankName2() {
		return bankName2;
	}

	public void setBankName2(String bankName2) {
		this.bankName2 = bankName2;
	}

	public List<DicItem> getLevels() {
		return levels;
	}

	public void setLevels(List<DicItem> levels) {
		this.levels = levels;
	}

	public float getPrize() {
		return prize;
	}

	public void setPrize(float prize) {
		this.prize = prize;
	}

	public String getThirdPassword() {
		return thirdPassword;
	}

	public void setThirdPassword(String thirdPassword) {
		this.thirdPassword = thirdPassword;
	}

	public List<DicItem> getAccountSubList() {
		return accountSubList;
	}

	public void setAccountSubList(List<DicItem> accountSubList) {
		this.accountSubList = accountSubList;
	}

	public String getJson() {
		return json;
	}

	public void setJson(String json) {
		this.json = json;
	}

	public DicItem getDicItem() {
		return dicItem;
	}

	public void setDicItem(DicItem dicItem) {
		this.dicItem = dicItem;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String[] getUserIds() {
		return userIds;
	}

	public void setUserIds(String[] userIds) {
		this.userIds = userIds;
	}

	public String getBuyAccount() {
		return buyAccount;
	}

	public void setBuyAccount(String buyAccount) {
		this.buyAccount = buyAccount;
	}

	public String getSaleAccount() {
		return saleAccount;
	}

	public void setSaleAccount(String saleAccount) {
		this.saleAccount = saleAccount;
	}

	public List getEpList() {
		return epList;
	}

	public void setEpList(List epList) {
		this.epList = epList;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	public EpComplain getEpComplain() {
		return epComplain;
	}

	public void setEpComplain(EpComplain epComplain) {
		this.epComplain = epComplain;
	}	
	
}



